package com.engc.common.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.engc.common.dao.BaseDao;
import com.engc.common.utils.BaseUtils;
import com.engc.common.utils.FilterGroup;
import com.engc.common.utils.ReadProperties;

/**
 * 数据权限Service层
 * 
 * @author guzhixiong
 * 
 */
public class DataPrivilegeRuleService {
	private BaseDao baseDao;
	// 全局，是否启用权限
	private static final boolean EnabledPermission = Boolean.valueOf(new ReadProperties("config/Global.properties").getValue("EnabledPermission"));

	/**
	 * 获取权限条件规则
	 * 
	 * @param view
	 * @return
	 */
	public FilterGroup GetRuleGroup(String view) {
		Map<String, Object> rolerecord = baseDao.Read("select datarule from sys_dataprivate where dataview=?", view);
		if (rolerecord == null || rolerecord.isEmpty()) {
			return null;
		}
		if (BaseUtils.isEmpty(rolerecord.get("datarule"))) {
			return null;
		} else {
			return JSON.parseObject(rolerecord.get("datarule").toString(), FilterGroup.class);
		}
	}
	
	

	/**
	 * 与业务数据合并数据规则
	 * 
	 * @param view
	 * @param rule
	 * @return
	 */
	public FilterGroup GetRuleGroup(boolean isadmin, String view, FilterGroup rule) {
		// 如果没有启用权限控制，不需要合并【数据权限】
		if (!EnabledPermission)
			return rule;
		// 如果是管理员，不需要合并【数据权限】
		if (isadmin)
			return rule;

		FilterGroup dpRule = GetRuleGroup(view);
		if (dpRule == null)
			return rule;
		FilterGroup resrule = new FilterGroup();
		resrule.setOp("and");
		List<FilterGroup> groups = new ArrayList<FilterGroup>();
		groups.add(rule);
		groups.add(dpRule);
		resrule.setGroups(groups);
		return resrule;
	}

	@Resource
	public void setBaseDao(BaseDao baseDao) {
		this.baseDao = baseDao;
	}

}
